import React, {useState, useEffect} from 'react'
import {Button, Modal, Row, Col, Input, Radio, Space, message} from 'antd'
import {history} from 'umi'
import moment from 'moment'
import {ArrowDownOutlined} from '@ant-design/icons'
import AdvancedSearchFrom from '@/components/SearchForm/advancedSearchFrom'
import AdvancedModal from '@/components/Modal/AdvancedModal'
import CustomTable from '@/components/Table'
import page from '../../page.less'
import styles from '../../styles.less'
import {getExtendedLeaseList, postExtendedLease} from '@/service/fiance/index'
import {downloadDocumentUrl} from '@/service/common/download'
import {getCookie} from '@/utils/cookie'
import {getCompany} from '@/service/common/index'
import {translateDataToTree} from '@/utils/common/index'
import {getDict} from '@/service/common/dict'

const formItemLayout = {
	labelCol: {flex: '100px'},
	wrapperCol: {flex: '1'},
}
function SettlementAudit() {
	const delayTypeList = [
		{key: 1, label: '无偿'},
		{key: 2, label: '有偿'},
	] // 延租类型
	const [selectId, setSelectId] = useState<any[]>([])
	const [idString, setIdString] = useState('')
	const [open, setOpen] = useState(false)
	const [selsetItem, setSelsetItem] = useState([]) // 选中数据集合
	const [state, setState] = useState<any>(0) // 默认同意结算
	const [idea, setIdea] = useState('') // 处理意见
	const [list, setList] = useState<any[]>([])
	const [formItem, setFormItem] = useState<any>({})
	const [companyData, setCompanyData] = useState<any[]>([])
	const [params, setParams] = useState({
		current: 1,
		size: 10,
	})
	// 搜索条件
	const [formValue, setFormValue] = useState({})
	const [dict, setDict] = useState({
		order_finance_delay_status: [], // 订单账单延租处理状态
	})
	// 分页数据
	const [total, setTotal] = useState([])
	const [currentPage, setCurrentPage] = useState({current: 1})
	// 获取列表数据
	const getList = (value: any, pages: any) => {
		getExtendedLeaseList({...pages, ...value}).then((res) => {
			if (res?.success) {
				setList(res?.data?.records)
				setTotal(res?.data?.total)
			}
		})
	}
	/** 获取所属公司数据 */
	const onCompany = () => {
		// eslint-disable-next-line react/destructuring-assignment
		// cookies中获取公司id
		const merchantIds: any = getCookie('orgId')
		getCompany({merchantId: merchantIds}).then((res: any) => {
			if (res?.success) {
				const lists = translateDataToTree(res?.data)
				setCompanyData(lists as any)
			}
		})
	}
	useEffect(() => {
		onCompany()
		getList({}, params)
		getDict(
			{
				dictKeys: ['order_finance_delay_status'],
			},
			(res: any) => {
				setDict(res)
			},
		)
	}, [])
	const formItems: any[] = [
		{
			type: 'group',
			key: 'group1',
			groupItems: [
				{
					type: 'input',
					label: '延租批次',
					name: 'delayBatch',
					key: 'delayBatch',
					keys: 'id',
					title: 'name',
					placeholder: '请输入延租批次',
				},
				{
					type: 'input',
					key: 'delayNo',
					name: 'delayNo',
					label: '延租单号',
					keys: 'key',
					title: 'label',
					placeholder: '请输入延租单号',
				},
				{
					type: 'input',
					key: 'plateNo',
					name: 'plateNo',
					label: '车牌号',
					placeholder: '请输入车牌号',
					keys: 'key',
					title: 'label',
				},
				{
					type: 'select',
					key: 'delayStatus',
					name: 'delayStatus',
					label: '处理状态',
					keys: 'dictKey',
					title: 'dictValue',
					items: dict?.order_finance_delay_status,
					placeholder: '请选择处理状态',
				},
			],
		},
		{
			type: 'group',
			key: 'group2',
			groupItems: [
				{
					type: 'dateRange',
					label: '申请日期',
					name: 'applyTime',
					key: 'applyTime',
					placeholder: '申请时间范围',
				},
				{
					type: 'input',
					key: 'driverName',
					name: 'driverName',
					label: '司机名称',
					keys: 'key',
					title: 'label',
				},
				{
					type: 'treeSelect',
					key: 'companyId',
					name: 'companyId',
					label: '所属公司',
					treeData: companyData,
					keys: 'id',
					title: 'name',
					placeholder: '请选择所属公司',
				},
				{
					type: 'input',
					key: 'orderCarNo',
					name: 'orderCarNo',
					label: '订单编号',
					keys: 'key',
					title: 'label',
				},
			],
		},
		{
			type: 'group',
			key: 'group3',
			groupItems: [
				{
					type: 'select',
					key: 'delayType',
					name: 'delayType',
					label: '延租类型',
					keys: 'key',
					title: 'label',
					items: delayTypeList,
					placeholder: '请选择延租类型',
				},
				{key: '1'},
				{key: '2'},
				{key: '3'},
			],
		},
	]
	const columns = [
		{
			title: '延租批次',
			dataIndex: 'delayBatch',
			key: 'delayBatch',
			align: 'center',
			width: 150,
		},
		{
			title: '延租单号',
			dataIndex: 'delayNo',
			key: 'delayNo',
			align: 'center',
			width: 250,
		},
		{
			title: '订单编号',
			dataIndex: 'orderCarNo',
			key: 'orderCarNo',
			align: 'center',
			width: 300,
		},
		{
			title: '处理状态',
			dataIndex: 'delayStatus',
			key: 'delayStatus',
			align: 'center',
			width: 150,
			render: (text: any) => (
				<>
					{dict?.order_finance_delay_status?.map(
						(item: {dictKey: string; dictValue: string}) => {
							if (item?.dictKey === text?.toString()) {
								return (
									<span key={item?.dictKey}>
										{item?.dictValue}
									</span>
								)
							}
							return ''
						},
					)}
				</>
			),
		},
		{
			title: '车牌号',
			dataIndex: 'plateNo',
			key: 'plateNo',
			align: 'center',
			width: 150,
		},
		{
			title: '司机名称',
			dataIndex: 'driverName',
			key: 'driverName',
			align: 'center',
			width: 150,
		},
		{
			title: '所属公司',
			dataIndex: 'companyName',
			key: 'companyName',
			align: 'center',
			width: 150,
		},
		{
			title: '申请时间',
			dataIndex: 'applyTime',
			width: 200,
			key: 'applyTime',
			align: 'center',
		},
		{
			title: '延租天数',
			dataIndex: 'delayCount',
			width: 100,
			key: 'delayCount',
			align: 'center',
			render: (text: any) => <>{text === 0 ? '--' : text}</>,
		},
		{
			title: '延租类型',
			dataIndex: 'delayType',
			width: 100,
			key: 'delayType',
			align: 'center',
			render: (text: number) => (
				<>{text === 1 ? <span>无偿</span> : <span>有偿</span>}</>
			),
		},
		{
			title: '延租日租金',
			dataIndex: 'rentAmount',
			width: 100,
			key: 'rentAmount',
			align: 'center',
			render: (text: any) => <>{text === 0 ? '--' : text}</>,
		},
		{
			title: '操作',
			dataIndex: '',
			width: 160,
			align: 'center',
			fixed: 'right',
			render: (_text: any, record: any) => (
				<>
					<Button
						size="small"
						type="link"
						onClick={() =>
							history.push(
								`/finance/delayRentAudit/detail?id=${record?.id}`,
							)
						}>
						查看
					</Button>
					{record?.delayStatus === 1 && (
						<Button
							type="link"
							size="small"
							onClick={() =>
								history.push(
									`/finance/delayRentAudit/examine?type?id=${record?.id}`,
								)
							}>
							审核
						</Button>
					)}
				</>
			),
		},
	]
	// 同意审核
	const onModalConfirm = () => {
		if (state) {
			const arr: any = []
			selsetItem?.forEach((res: any) => {
				arr.push(res?.delayNo)
			})
			const data = {
				delayNo: arr,
				delayStatus: state,
				handleRemark: idea,
			}
			postExtendedLease(data).then((res: any) => {
				if (res?.success) {
					message.success(res?.msg)
					setSelectId([])
					setIdString('')
					setSelsetItem([])
					getList({}, params)
					setFormValue({})
					setFormItem({})
					setState(undefined)
					setIdea('')
					setOpen(false)
					
				} else {
					setOpen(false)
				}
			})
		} else {
			message.warning('请选择处理状态')
		}
	}
	// 搜索
	const finish = (value: any) => {
		const info = {...value}
		if (value?.applyTime) {
			info.applyStartTime = moment(value?.applyTime[0]).format(
				'YYYY-MM-DD HH:mm:ss',
			)
			info.applyEndTime = moment(value?.applyTime[1]).format(
				'YYYY-MM-DD HH:mm:ss',
			)
		}
		delete info.applyTime
		const data = {
			current: 1,
			size: 10,
		}
		setFormItem(info)
		setCurrentPage({current: 1})
		getList(info, data)
	}
	// 清空
	const reset = () => {
		const data = {
			current: 1,
			size: 10,
		}
		setCurrentPage({current: 1})
		getList({}, data)
	}
	return (
		<>
			<div className={`${page.card} ${page.page} searchFrom`}>
				<AdvancedSearchFrom
					formLayout={formItemLayout}
					onFinish={finish}
					onReset={reset}
					formItems={formItems}
					rows={3}
					values={formValue}
				/>
				<div className={page.list}>
					<Button
						icon={<ArrowDownOutlined />}
						style={{color: '#9A59FF', borderColor: '#9A59FF'}}
						ghost
						size="small"
						onClick={() => {
							downloadDocumentUrl({
								resourceId: '157',
								queryDesc: '延租列表导出,resourceId:157',
								queryParam: formItem,
							})
						}}>
						导出
					</Button>
					<Button
						style={{
							color: '#9A59FF',
							borderColor: '#9A59FF',
							marginLeft: '10px',
						}}
						ghost
						size="small"
						onClick={() => {
							if (selectId.length === 0) {
								Modal.confirm({
									title: '延租审核',
									content: '请先勾选要延租的单！',
									okText: () => {},
									cancelText: '关闭',
								})
								return
							}
							setOpen(true)
							const arr1: any = []
							selsetItem?.forEach((res: any) => {
								arr1.push(res?.delayNo)
							})
							setIdString(() => arr1.join(','))
						}}>
						一键审核
					</Button>
					<CustomTable
						kid="delayNo"
						pagination
						clearSelection
						total={total}
						callback={(param: any) => {
							setParams(param)
							const data = {
								current: param?.current,
							}
							setCurrentPage(data)
							getList(formItem, param)
						}}
						params={currentPage}
						columns={columns}
						dataSource={list}
						showRowSelection
						selectCallback={(text: any, datas: any) => {
							setSelectId(text)
							setSelsetItem(datas)
						}}
						getCheckboxProps={{
							getCheckboxProps: (record: any) => {
								if (record?.delayStatus !== 1) {
									return {disabled: true}
								}
								return null
							},
						}}
					/>
				</div>
				<AdvancedModal
					isOpen={open}
					title="延租审核"
					setIsOpen={setOpen}
					footer={null}
					width="650px">
					<Row>
						<Col
							span={24}
							className={`${styles.flex} ${styles.row}`}>
							已选择延租单号：{idString}
						</Col>
						<Col
							span={24}
							className={`${styles.flex} ${styles.row}`}>
							<span className={styles.processingStatus}>
								处理状态：
							</span>
							<Radio.Group
								defaultValue={state}
								onChange={({target: {value}}) =>
									setState(value)
								}>
								<Radio value={1}>同意延租</Radio>
								<Radio value={2}>拒绝延租</Radio>
							</Radio.Group>
						</Col>
						<Col
							span={24}
							className={`${styles.flex} ${styles.row}`}>
							<span style={{textIndent: '11px'}}>处理意见：</span>
							<Input.TextArea
								allowClear
								showCount
								maxLength={200}
								placeholder="请输入处理意见，不超过200个字符"
								onChange={({target: {value}}) => {
									setIdea(value)
								}}
								defaultValue={idea}
								style={{width: '70%'}}
							/>
						</Col>
					</Row>
					<Row justify="center">
						<Space>
							<Button onClick={() => setOpen(false)}>关闭</Button>
							<Button type="primary" onClick={onModalConfirm}>
								确定
							</Button>
						</Space>
					</Row>
				</AdvancedModal>
			</div>
		</>
	)
}
export default SettlementAudit
